<?php

namespace App\Http\Services;

use App\Http\Model\FinanceCharm;
use App\Http\Model\FinanceRoomWealth;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\FinanceWealth;
use App\Http\Model\Room;
use App\Http\Model\User;
use Illuminate\Support\Facades\Log;

class MaximumGoldServices extends CommonServices
{
    /**
     * @var User
     */
    protected $user;

    /**
     * @var FinanceCharm
     */
    protected $charm;

    /**
     * @var FinanceWealth
     */
    protected $wealth;

    /**
     * @var FinanceRoomWealth
     */
    protected $room_wealth;

    /**
     * @var FinanceUserWallet
     */
    protected $model_finance_user_wallet;

    /**
     * @var Room
     */
    protected $model_room;

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
        $this->charm = new FinanceCharm();
        $this->user = new User();
        $this->model_finance_user_wallet = new FinanceUserWallet();
        $this->wealth = new FinanceWealth();
        $this->room_wealth = new FinanceRoomWealth();
        $this->model_room = new Room();
    }

    /**
     * Created at 2021/12/13 11:19
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param $type
     * @param $page
     * @param $page_size
     * @return array
     */
    public function getCharmCharts($type, $page, $page_size): array
    {
        $max_count = 50;
        if ($type == 3) {
            $max_count = 100;
        }

        $page_index = $page * $page_size;
        if ($page_index > $max_count - 1) {
            return ['list' => [], 'page_index' => $page, 'page_count' => 0, 'page_size' => $page_size];
        }

        if ($page_index + $page_size > $max_count) {
            $page_size = $max_count - $page_index;
        }

        if ($page_size == 0) {
            return ['list' => [], 'page_index' => $page, 'page_count' => 0, 'page_size' => $page_size];
        }

        $charts = $this->charm->get_user_charts_maximum_gold($type, $page_index, $page_size);
        //昨天/上周/上个月 魅力榜
        $before_charts = $this->charm->get_before_user_charts_maxmium_gold($type, 0, 3);
        $now_list_id = array_keys($charts);
        $before_list_id = array_keys($before_charts);
        $list_id = array_merge($now_list_id, $before_list_id);
        $map_user = [];
        $map_wallet = [];

        $users = $this->user->get_users_by_ids($list_id);
        for ($i = 0; $i < count($users); $i++) {
            $map_user[$users[$i]['user_id']] = $users[$i];
        }
        $wallets = $this->model_finance_user_wallet->get_wallets($list_id);
        for ($i = 0; $i < count($wallets); $i++) {
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }

        $data = [];
        foreach ($charts as $k => $v) {
            if (empty($map_user[$k])) {
                continue;
            }

            $item = $map_user[$k];
            $item['diamond_balance'] = $map_wallet[$k]['diamond_balance'];
            $item['charm_balance'] = $map_wallet[$k]['charm_balance'];
            $item['wealth_balance'] = $map_wallet[$k]['wealth_balance'];
            $item['total_charm_value'] = $v;
            $data[] = $item;
        }

        $data_before = [];
        foreach ($before_charts as $kk => $vv) {
            if (empty($map_user[$kk])) {
                continue;
            }

            $item = $map_user[$kk];
            $item['diamond_balance'] = $map_wallet[$kk]['diamond_balance'];
            $item['charm_balance'] = $map_wallet[$kk]['charm_balance'];
            $item['wealth_balance'] = $map_wallet[$kk]['wealth_balance'];
            $item['total_charm_value'] = $vv;
            $data_before[] = $item;
        }

        $user = $this->user->get_current_user();
        $count = 0;
        $rank_50 = $this->charm->get_user_charts_maximum_gold($type, 0, 50);
        foreach ($rank_50 as $kk => $vv) {
            $count++;
            if ($kk == $user['user_id']) {
                break;
            }
        }

        if (!empty($user)) {
            $my_charm = $this->charm->get_my_chart_maximum_gold($type, $user['user_id']);
            $my_wallet = $this->model_finance_user_wallet->get_wallet($user['user_id']);
            $user['diamond_balance'] = $my_wallet['diamond_balance'];
            $user['charm_balance'] = $my_wallet['charm_balance'];
            $user['wealth_balance'] = $my_wallet['wealth_balance'];
            $user['total_charm_value'] = $my_charm;
            $user['charm_rank'] = ($count >= 50 || $my_charm < 1) ? -1 : $count;
        }

        return ['list' => $data, 'page_index' => $page, 'page_count' => count($data), 'page_size' => $page_size, 'before_list' => $data_before, 'my' => $user];
    }

    /**
     * Created at 2021/12/13 11:46
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param $type
     * @param $page
     * @param $page_size
     * @return array
     */
    public function getWealthCharts($type, $page, $page_size): array
    {
        $max_count = 50;
        if ($type == 3) {
            $max_count = 100;
        }

        $page_index = $page * $page_size;
        if ($page_index > $max_count - 1) {
            return ['list' => [], 'page_index' => $page, 'page_count' => 0, 'page_size' => $page_size];
        }

        if ($page_index + $page_size > $max_count) {
            $page_size = $max_count - $page_index;
        }

        if ($page_size == 0) {
            return ['list' => [], 'page_index' => $page, 'page_count' => 0, 'page_size' => $page_size];
        }

        $charts = $this->wealth->get_user_charts_maximum_gold($type, $page_index, $page_size);
        //昨天/上周/上个月 富豪榜
        $before_charts = $this->wealth->get_before_user_charts_maximum_gold($type, 0, 3);

        $now_list_id = array_keys($charts);
        $before_list_id = array_keys($before_charts);
        $list_id = array_merge($now_list_id, $before_list_id);
        $map_user = [];
        $map_wallet = [];
        $data = [];

        $users = $this->user->get_users_by_ids($list_id);
        for ($i = 0; $i < count($users); $i++) {
            $map_user[$users[$i]['user_id']] = $users[$i];
        }

        $wallets = $this->model_finance_user_wallet->get_wallets($list_id);
        for ($i = 0; $i < count($wallets); $i++) {
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }

        foreach ($charts as $k => $v) {
            if (empty($map_user[$k])) {
                continue;
            }
            $item = $map_user[$k];
            $item['diamond_balance'] = $map_wallet[$k]['diamond_balance'];
            $item['charm_balance'] = $map_wallet[$k]['charm_balance'];
            $item['wealth_balance'] = $map_wallet[$k]['wealth_balance'];
            $item['total_wealth_value'] = intval($v);
            $data[] = $item;
        }

        $data_before = [];
        foreach ($before_charts as $kk => $vv) {
            if (empty($map_user[$kk])) {
                continue;
            }
            $item = $map_user[$kk];
            $item['diamond_balance'] = $map_wallet[$kk]['diamond_balance'];
            $item['charm_balance'] = $map_wallet[$kk]['charm_balance'];
            $item['wealth_balance'] = $map_wallet[$kk]['wealth_balance'];
            $item['total_wealth_value'] = $vv;
            $data_before[] = $item;
        }

        $user = $this->user->get_current_user();
        $rank_50 = $this->wealth->get_user_charts_maximum_gold($type, 0, 50);
        $count = 0;
        foreach ($rank_50 as $kk => $vv) {
            $count++;
            if ($kk == $user['user_id']) {
                break;
            }
        }

        if (!empty($user)) {
            $my_wealth = $this->wealth->get_my_chart_maximum_gold($type, $user['user_id']);
            $my_wallet = $this->model_finance_user_wallet->get_wallet($user['user_id']);
            $user['diamond_balance'] = $my_wallet['diamond_balance'];
            $user['charm_balance'] = $my_wallet['charm_balance'];
            $user['wealth_balance'] = $my_wallet['wealth_balance'];
            $user['total_wealth_value'] = $my_wealth;
            $user['wealth_rank'] = ($count >= 50 || $my_wealth < 1) ? -1 : $count;
        }

        return ['list' => $data, 'page_index' => $page, 'page_count' => count($data), 'page_size' => $page_size, 'before_list' => $data_before, 'my' => $user];
    }

    /**
     * Created at 2021/12/13 11:55
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param $type
     * @param $page
     * @param $page_size
     * @return array
     */
    public function getRoomSelfWealthCharts($type, $page, $page_size): array
    {
        $max_count = 50;
        if ($type == 3) {
            $max_count = 100;
        }

        $page_index = $page * $page_size;
        if ($page_index > $max_count - 1) {
            return ['list' => [], 'page_index' => $page, 'page_count' => 0, 'page_size' => $page_size];
        }

        if ($page_index + $page_size > $max_count) {
            $page_size = $max_count - $page_index;
        }

        if ($page_size == 0) {
            return ['list' => [], 'page_index' => $page, 'page_count' => 0, 'page_size' => $page_size];
        }

        $charts = $this->room_wealth->get_room_charts_maximum_gold($type, $page_index, $page_size);
        //昨天/上周/上个月 富豪榜
        $before_charts = $this->room_wealth->get_before_room_charts_maximum_gold($type, 0, 3);
        $now_list_romm_id = array_keys($charts);
        $before_list_room_id = array_keys($before_charts);
        $list_room_id = array_merge($now_list_romm_id, $before_list_room_id);
        $map_room = [];
        $data = [];
        $rooms = $this->model_room->get_rooms_by_ids($list_room_id);
        for ($i = 0; $i < count($rooms); $i++) {
            $map_room[$rooms[$i]['room_id']] = $rooms[$i];
        }

        foreach ($charts as $k => $v) {
            $item = $map_room[$k];
            $item['total_wealth_value'] = intval($v);
            $data[] = $item;
        }

        $before_data = [];
        foreach ($before_charts as $kk => $vv) {
            $item = $map_room[$kk];
            $item['total_wealth_value'] = intval($vv);
            $before_data[] = $item;
        }

        return ['list' => $data, 'page_index' => $page, 'page_count' => count($data), 'page_size' => $page_size, 'before_list' => $before_data];
    }

    /**
     * 修复最多金月榜缓存
     */
    public function updateMonthChartsCache ($endTime, $type = 0, $roomIds = array()) {
        Log::info('updateMonthChartsCache 开始执行');
        try {
            echo "开始：\n";
            $maximumGoldRoomServices = new  MaximumGoldRoomServices();
            $maximumGoldRoomIds = array();
            if (count($roomIds) > 0) {
                $maximumGoldRoomIds = $roomIds;
            } else {
                $maximumGoldRoomIds = $maximumGoldRoomServices->getRoomIds();
            }
            echo "房间编号:" . json_encode($maximumGoldRoomIds) . "\n";
            $this->MaxGoldMonthChart($maximumGoldRoomIds, $endTime, $type);
            $this->MaxGoldWeekChart($maximumGoldRoomIds, $endTime, $type);
            $this->MaxGoldDayChart($maximumGoldRoomIds, $endTime, $type);
            echo "结束";
            //$this->MaxGoldAllChart($maximumGoldRoomIds, $endTime, $type);
        } catch (\Exception $e) {
            echo  $e->getMessage();
            //Log::error('11', "updateMonthChartsCache" . $e->getMessage(), $e);
        }
        Log::info('updateMonthChartsCache 结束执行');
    }

    // 最多金--月榜
    private function MaxGoldMonthChart($maxGoldRoomIds, $benchmark, $type = 0) {
        $strMonth = date("Ym", $benchmark);

        // 获取本月firstday  TODO 存在误差 毫秒值
        $firstDay = date('Y-m-01 00:00:00', time());
        $lastDay = date('Y-m-d H:i:s', $benchmark);
        echo '月榜开始：$firstDay：' . $firstDay . ';$lastDay:' . $lastDay . "\n";
        echo '月榜时间：key：' . $strMonth . "\n";
        foreach ($maxGoldRoomIds  as $k=>$roomId) {
            $charms = $this->charm->getCharmListByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            echo '月榜人气：$roomId:' . $roomId .',$charms:' . json_encode($charms) . "\n";
            foreach ($charms as $vc) {
                if ($vc->sumValue) {
                    $charmValue = $vc->sumValue * 10;
                    if ($type == 1) {
                        $charmValue = 0 - $charmValue;
                    }
                    $this->charm->updateMonthCache($strMonth, $charmValue, $vc->user_id);
                }
            }

            $wealth = $this->wealth->getWealthByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            echo '月榜财富：$roomId:' . $roomId .',$wealth:' . json_encode($wealth) . "\n";
            foreach ($wealth as $vw) {
                if ($vw->sumValue) {
                    $wealthValue = $vw->sumValue * 10;
                    if ($type == 1) {
                        $wealthValue = 0 - $wealthValue;
                    }
                    $this->wealth->updateMonthCache($strMonth, $wealthValue, $vw->user_id);
                }
            }

            $roomWealth = $this->room_wealth->getRoomWealthByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            echo '月榜房间财富：$roomId:' . $roomId .',$roomWealth:' . json_encode($roomWealth) . "\n";
            foreach ($roomWealth as $vr) {
                if ($vr->sumValue) {
                    $wealthValue = $vr->sumValue;
                    if ($type == 1) {
                        $wealthValue = 0 - $wealthValue;
                    }
                    $this->room_wealth->updateMonthCache($strMonth, $wealthValue, $roomId);
                }
            }
        }

        echo "月榜结束\n";

    }

    // 最多金--周榜
    private function MaxGoldWeekChart($maxGoldRoomIds, $benchmark, $type = 0) {
        $strDay = date("Ymd");
        $first = 1;
        $w = date('w',strtotime($strDay));
        $strWeekStart = date('Ymd',strtotime("$strDay -".($w ? $w - $first : 6).' days'));
        $strWeekEnd = date('Ymd',strtotime("$strWeekStart +6 days"));

        $firstDay = date('Y-m-d 00:00:00', strtotime($strWeekStart));
        $lastDay = date('Y-m-d H:i:s', $benchmark);
        echo '周榜开始：$firstDay：' . $firstDay . ';$lastDay:' . $lastDay . "\n";
        echo '周榜时间：key：' . $strWeekStart . ',' . $strWeekEnd . "\n";
        foreach ($maxGoldRoomIds  as $k=>$roomId) {
            $charms = $this->charm->getCharmListByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            echo '周榜人气：$roomId:' . $roomId .',$charms:' . json_encode($charms) . "\n";
            foreach ($charms as $vc) {
                if ($vc->sumValue) {
                    $charmValue = $vc->sumValue * 10;
                    if ($type == 1) {
                        $charmValue = 0 - $charmValue;
                    }
                    $this->charm->updateWeekCache($strWeekStart, $strWeekEnd, $charmValue, $vc->user_id);
                }
            }

            $wealth = $this->wealth->getWealthByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            echo '周榜财富：$roomId:' . $roomId .',$wealth:' . json_encode($wealth) . "\n";
            foreach ($wealth as $vw) {
                if ($vw->sumValue) {
                    $wealthValue = $vw->sumValue * 10;
                    if ($type == 1) {
                        $wealthValue = 0 - $wealthValue;
                    }
                    $this->wealth->updateWeekCache($strWeekStart, $strWeekEnd, $wealthValue, $vw->user_id);
                }
            }

            $roomWealth = $this->room_wealth->getRoomWealthByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            echo '周榜房间财富：$roomId:' . $roomId .',$roomWealth:' . json_encode($roomWealth) . "\n";
            foreach ($roomWealth as $vr) {
                if ($vr->sumValue) {
                    $wealthValue = $vr->sumValue;
                    if ($type == 1) {
                        $wealthValue = 0 - $wealthValue;
                    }
                    $this->room_wealth->updateWeekCache($strWeekStart, $strWeekEnd, $wealthValue, $roomId);
                }
            }
        }

        echo "周榜结束\n";
    }

    // 最多金--日榜
    private function MaxGoldDayChart($maxGoldRoomIds, $benchmark, $type = 0) {

        $strDay = date('Ymd');
        $firstDay = date('Y-m-d 00:00:00', time());
        $lastDay = date('Y-m-d H:i:s', $benchmark);

        echo '日榜开始：$firstDay：' . $firstDay . ';$lastDay:' . $lastDay . "\n";
        echo '日榜时间：key：' . $strDay . "\n";
        foreach ($maxGoldRoomIds  as $k=>$roomId) {
            $charms = $this->charm->getCharmListByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            echo '日榜人气：$roomId:' . $roomId .',$charms:' . json_encode($charms) . "\n";
            foreach ($charms as $vc) {
                if ($vc->sumValue) {
                    $charmValue = $vc->sumValue * 10;
                    if ($type == 1) {
                        $charmValue = 0 - $charmValue;
                    }
                    $this->charm->updateDayCache($strDay, $charmValue, $vc->user_id);
                }
            }

            $wealth = $this->wealth->getWealthByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            echo '日榜财富：$roomId:' . $roomId .',$wealth:' . json_encode($wealth) . "\n";
            foreach ($wealth as $vw) {
                if ($vw->sumValue) {
                    $wealthValue = $vw->sumValue * 10;
                    if ($type == 1) {
                        $wealthValue = 0 - $wealthValue;
                    }
                    $this->wealth->updateDayCache($strDay, $wealthValue, $vw->user_id);
                }
            }

            $roomWealth = $this->room_wealth->getRoomWealthByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            echo '日榜房间财富：$roomId:' . $roomId .',$roomWealth:' . json_encode($roomWealth) . "\n";
            foreach ($roomWealth as $vr) {
                if ($vr->sumValue) {
                    $wealthValue = $vr->sumValue;
                    if ($type == 1) {
                        $wealthValue = 0 - $wealthValue;
                    }
                    $this->room_wealth->updateDayCache($strDay, $wealthValue, $roomId);
                }
            }
        }
        echo "日榜结束\n";
    }

    // 最多金--全榜
    private function MaxGoldAllChart($maxGoldRoomIds, $benchmark, $type = 0) {

        $firstDay = date('Y-m-d 00:00:00');
        $lastDay = date('Y-m-d H:i:s', $benchmark);


        foreach ($maxGoldRoomIds  as $k=>$roomId) {
            $charms = $this->charm->getCharmListByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            foreach ($charms as $v) {
                if ($v->charm_value) {
                    $charmValue = $v->sumValue * 10;
                    if ($type == 1) {
                        $charmValue = 0 - $charmValue;
                    }
                    $this->charm->updateAllCache($charmValue, $v->user_id);
                }
            }

            $wealth = $this->wealth->getWealthByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            foreach ($wealth as $v) {
                if ($v->wealth_value) {
                    $wealthValue = $v->sumValue * 10;
                    if ($type == 1) {
                        $wealthValue = 0 - $wealthValue;
                    }
                    $this->wealth->updateAllCache($wealthValue, $v->user_id);
                }
            }

            $roomWealth = $this->room_wealth->getRoomWealthByRoomId($roomId, strtotime($firstDay), strtotime($lastDay));
            foreach ($roomWealth as $v) {
                if ($v->wealth_value) {
                    $wealthValue = $v->sumValue;
                    if ($type == 1) {
                        $wealthValue = 0 - $wealthValue;
                    }
                    $this->room_wealth->updateAllCache($wealthValue, $roomId);
                }
            }
        }
    }

}